//
// Created by jinyf on 2022/3/2.
//

#include "MNCallJava.h"


MNCallJava::MNCallJava(JavaVM *_jvm, JNIEnv *_jEnv, jobject *_jobj) {


    this->jVM=_jvm;
    this->jEnv=_jEnv;
    this->jobj=*_jobj;

    //jobject会被JNI回收，因为是个弱引用，导致野指针，所以要保存为全局引用
    jobject glObj=jEnv->NewGlobalRef(*_jobj);
    this->jobj = glObj;

    jclass jclz=jEnv->GetObjectClass(*_jobj);

    if (!jclz){

        if (LOG_DEBUG){
            LOGE("get class error");
        }

        return;
    }


    jmethodId_prepared=jEnv->GetMethodID(jclz,"onCallPrepared","()V");
    jmid_timeinfo=jEnv->GetMethodID(jclz,"onCallTimeInfo", "(II)V");

}

MNCallJava::~MNCallJava() {

}

void MNCallJava::onCallPrepared(int type) {
    if(type == MAIN_THREAD)
    {
        jEnv->CallVoidMethod(jobj, jmethodId_prepared);
    }
    else if(type == CHILD_THREAD)
    {
        JNIEnv *jniEnv=NULL;
        if(jVM->AttachCurrentThread(&jniEnv, 0) != JNI_OK)
        {
            if(LOG_DEBUG)
            {
                LOGE("get child thread jnienv worng");
            }
            return;
        }
        jniEnv->CallVoidMethod(jobj, jmethodId_prepared);
        jVM->DetachCurrentThread();
    }
}

//回调   java
void MNCallJava::onCallTimeInfo(int type, int curr, int total) {
    if (type == MAIN_THREAD) {
        jEnv->CallVoidMethod(jobj, jmid_timeinfo, curr, total);
    } else if (type == CHILD_THREAD) {
        JNIEnv *jniEnv;
        if (jVM->AttachCurrentThread(&jniEnv, 0) != JNI_OK) {
            if (LOG_DEBUG) {
                LOGE("call onCallTimeInfo worng");
            }
            return;
        }
        jniEnv->CallVoidMethod(jobj, jmid_timeinfo, curr, total);
        jVM->DetachCurrentThread();
    }
}
